<template>
  <div class="dashboard-container">
    <div class="app-container">
      <pageTools :show-before="true">
        <span slot="before">{{ page.total }}条信息</span>
        <template #after>
          <el-button type="success" @click="$router.push('/import')">导入</el-button>
          <el-button type="danger" @click="exportData">导出</el-button>
          <el-button type="primary" @click="showDialog = true">新增</el-button>
        </template>
      </pageTools>
      <el-card class="main-card">
        <el-table border :data="list">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="头像" sortable="">
            <template slot-scope="{ row }">
              <img
                slot="reference"
                v-imageError="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                alt=""
                @click="showQrCodefun(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="">
            <template slot-scope="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="">
            <template>
              <el-switch :value="true" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{ row }">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :current-page="page.page"
            :page-size="page.size"
            :total="page.total"
            @current-change="changepage"
          />
        </el-row>
      </el-card>
      <addEmployee :show-dialog="showDialog" @getEmployeeList="getEmployeeList" @loseDialog="showDialog = false" />
      <el-dialog title="二维码" :visible.sync="showQrCode">
        <el-row type="flex" justify="center">
          <canvas ref="canvas" />
        </el-row>
      </el-dialog>
      <assignRole ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import addEmployee from './components/add-employee.vue'
import assignRole from './components/assign-role.vue'
import QrCode from 'qrcode'
export default {
  components: {
    addEmployee,
    assignRole
  },
  data() {
    return {
      loading: false,
      list: [],
      page: {
        page: 1,
        size: 5,
        total: 0
      },
      showDialog: false,
      showQrCode: false,
      showRoleDialog: false,
      userId: null
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // 获取列表
    async getEmployeeList() {
      this.loading = true
      const { total, rows } = await getEmployeeList(this.page)
      this.list = rows
      this.page.total = total
      this.loading = false
    },
    // 换页
    changepage(page) {
      console.log(page)
      this.page.page = page
      this.getEmployeeList()
    },
    // 聘用形式格式化
    formatEmployment(row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find(item => item.id === parseInt(cellValue))

      return obj ? obj.value : '未知'
    },
    async delEmployee(id) {
      console.log(id)
      try {
        await this.$confirm('您确定删除该员工吗')
        await delEmployee(id)
        this.getEmployeeList()
        this.$message.success('删除员工成功')
      } catch (error) {
        console.log(error)
      }
    },
    exportData() {
      //  做操作
      // 表头对应关系
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 懒加载
      import('@/vendor/Export2Excel').then(async excel => {
        const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
        // [["张三", "13811"，"2018","1", "2018", "10002"],["李思", "139811"，"2018","1", "2018", "10002"],...]
        const data = this.formatJson(headers, rows)

        excel.export_json_to_excel({
          header: Object.keys(headers),
          data,
          filename: '员工信息表',
          autoWidth: true,
          bookType: 'xlsx'

        })
      })
    },
    // 该方法负责将数组转化成二维数组
    formatJson(headers, rows) {
      // 首先遍历数组
      return rows.map(item => {
        return Object.keys(headers).map(key => {
          return item[headers[key]]
        }) // => ["张三", "13811"，"2018","1", "2018", "10002"]
      })
    },
    // 二维码生成
    showQrCodefun(url) {
      console.log(url)
      // 确保url内有值
      if (url) {
        this.showQrCode = true
        this.$nextTick(() => {
          QrCode.toCanvas(this.$refs.canvas, url)
        })
      } else {
        this.$message.error('该用户暂时没有上传头像')
      }
    },
    // 角色分配
    async editRole(id) {
      this.userId = id
      await this.$refs.assignRole.getUserDetailById(id)
      this.showRoleDialog = true
    }
  }
}
</script>

<style>
  .main-card{
    margin-top: 20px;
  }
</style>
